'use strict';
var express = require('express');
var router = express.Router();
var request = require('request');
var async = require('async');
var logger = require('../logger');
var superagent = require('superagent');
var jwt = require('jsonwebtoken');
var mongo = require('mongoskin');
var http = require("http");
var redis = require("redis");
var client = redis.createClient(6379,"127.0.0.1");


var db = mongo.db("mongodb://localhost:27017/cet");
db.bind('cet');

// function test(req, res, next){
//     var id = req.body.id;
//     var baseUrl = "http://www.chsi.com.cn/cet/ValidatorIMG.JPG?ID=7922.820615679844"

    
//     superagent.get(baseUrl)
//     .end(function(err, sres){
//         res.send(sres)
//         var cookie = sres.header['set-cookie'];
//         console.log(cookie)
//         var data = sres.text.match((/\"(.*)\"/));
//         console.log(data[1]);
//         res.send({cookie: cookie, yzmUrl:data[1]});
//     })
// }

// function testQuery(req, res, next){
//     var data = req.body.data;
//     console.log(data)
//     var v = req.body.v;
//     var cookie = req.body.cookie;
//     var url = "http://cache.neea.edu.cn/cet/query";
//     superagent.post(url)
//     .set('Cookie',cookie)
//     .set('Referer', "http://cet.neea.edu.cn/cet/")
//     .set("Origin", "http://cet.neea.edu.cn")
//     .send({
//         data: data,
//         v: v
//     })
//     .end(function(err,sres){
//         res.send(sres)
//     })
// }


function cet (req, res, next)
{
    var zkzh = req.body.zkzh;//准考证号
    var xm = req.body.xm;//姓名
    var yzm = req.body.yzm;//验证码
    var cookie = req.body.cookie;
    var baseUrl =  "http://www.chsi.com.cn/cet/query";
    let formData = {
        zkzh: zkzh,
        xm: xm,
        yzm: yzm
    }
    // console.log(formData)
    try{
        // 请求
        superagent.post(baseUrl)  
            .set("Referer","http://www.chsi.com.cn/cet/")
            .set('Cookie',cookie)
            .type("form")
            .send(formData)
            .end(function (err, sres) {
                var all = sres.text;
                //切割html
                var listenAndSpeak = cut(all,"听<span class='space_long'>&nbsp;</span>力","<td>","</td>")
                var reading = cut(all,"阅<span class='space_long'>&nbsp;</span>读","<td>","</td>")
                var writing = cut(all,"写作和翻译","<td>","</td>")
                var total = cut(all,"总<span class='space'>&nbsp;</span>分",'<span class="colorRed">',"</span>")
                var level = cutForLevel(all,"考试级别","</td>")
                var date = cutForDate(all, '<div class="m_l" id="leftH">', '<h2>','</h2>')
                let data = {'听说':listenAndSpeak, '阅读理解':reading, '写作和翻译':writing, '级数':level, '总分':total, '时间':date} 
                data.zkzh = zkzh;// 准考证号
                data.xm = xm;//姓名
                db.cet.insert(data)//插入数据库
                // console.log(all)
                res.send({ code:200, message:'ok', data:data })

            })
    }catch(err){
        res.send({ code:500,message:'未知错误' + err})
    }
}

/**
 * 切割分数
 * @param {string} str 
 * @param {string} start 
 * @param {string} middle 
 * @param {string} end 
 */
function cut(str,start,middle,end){
	var stepOne = str.slice(str.indexOf(start)+start.length,str.indexOf(end,str.indexOf(start)+start.length))
	var stepTwo = stepOne.slice(stepOne.indexOf(middle)+middle.length)
	return parseInt(stepTwo) 
}

/**
 * 切割等级
 * @param {string} str 
 * @param {string} start 
 * @param {string} end 
 */
function cutForLevel(str,start,end){
	// console.log('<td colspan="2">'.length)
	var stepOne = str.slice(str.indexOf(start),str.indexOf(end,str.indexOf(start)))
	if (stepOne.match("英语四级")) {return "英语四级"}
	else if (stepOne.match("英语六级")) {return "英语六级"}
	else return "false"
}

function cutForDate(str, start, middle, end)
{
    var stepOne = str.slice( str.indexOf(start) + start.length, str.indexOf(end, str.indexOf(start) + start.length) )
    var stepTwo = stepOne.slice( stepOne.indexOf(middle) + middle.length)
    // console.log(stepTwo)
    var year = parseInt(stepTwo)+"年"
    if(stepOne.match('上半年')){
        return year+'6月17日'
    }else if(stepOne.match('下半年')){
        return year+'12月16日'
    }else{
        return false;
    }
}



module.exports = {cet };
